Home:ALL Converter>rest_framework_jwt | Return custom error message in case of token verification failure

rest_framework_jwt | Return custom error message in case of token verification failure

Ask Time:2021-01-15T01:35:25         Author:gautamw3

Json Formatter

I am using rest_framework_jwt in order to implement token based authentication within my API project based on Django Rest Framework and Python programming language.

The issue I am facing right now is that I am getting a random error in response in case an expired token is passed in the header with an API request. I am wandering how I can override that error throwing function and return my own custom response from there.

I am getting currently in response is : {"detail": "Signature has expired."}

I went through the rest_framework_jwt documentation and found the codes responsible behind throwing that failure response. I tried to change the response object from there but it didn't work and I ran into some other random error.

I tried then creating a middleware and there I succeed in returning custom response in case of token verification failure. But now I am unable to login to the system.

Codes for the middleware I created are:

import jwt
from django.utils.encoding import smart_text
from django.utils.translation import ugettext as _
from django.http import JsonResponse
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from rest_framework import exceptions
from rest_framework.authentication import (
    get_authorization_header
)

jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
jwt_get_username_from_payload = api_settings.JWT_PAYLOAD_GET_USERNAME_HANDLER


class CheckIfTokenIsValid(BaseJSONWebTokenAuthentication):
    www_authenticate_realm = 'api'

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print(request.path)
        if request.path.startswith('/dashboard/'):
            print("CHECKKKKKK")
            return None
        else:
            jwt_value = self.get_jwt_value(request)
            if jwt_value is None:
                return JsonResponse({'status_code': 404, 'message': 'Token not found'})
            try:
                payload = jwt_decode_handler(jwt_value)
            except jwt.ExpiredSignature:
                return JsonResponse({'status_code': 406, 'message': 'Token expired'})
            except jwt.DecodeError:
                return JsonResponse({'status_code': 406, 'message': 'Token decode error'})
            except jwt.InvalidTokenError:
                return JsonResponse({'status_code': 406, 'message': 'Invalid token'})
        return None
 
    def get_jwt_value(self, request):
        auth = get_authorization_header(request).split()
        auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower()

        if not auth:
            if api_settings.JWT_AUTH_COOKIE:
                return request.COOKIES.get(api_settings.JWT_AUTH_COOKIE)
            return None

        if smart_text(auth[0].lower()) != auth_header_prefix:
            return None

        if len(auth) == 1:
            msg = _('Invalid Authorization header. No credentials provided.')
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid Authorization header. Credentials string '
                    'should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        return auth[1]

I am unable to understand what exactly needs to be returned by this middleware in case everything goes fine with the supplied token.

Do anyone here has an effective solution to my problem please. Any sort of solution by anyone will be of great help.

Please don't mind my silly coding skills and kindly ignore my mistakes as I am new to this Django thing :)

Thanks

Author:gautamw3,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/65724047/rest-framework-jwt-return-custom-error-message-in-case-of-token-verification-f
yy